package com.lj.demo.springbootshirojwt.util;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * Title: 处理http请求工具类
 * Description:
 * Date: 2019年07月04日 14:14
 *
 * @author lvjie@hiynn.com
 * @version 1.0
 * Significant Modify：
 * Date                  Author                 Content
 * =================================================================
 * 2019年07月04日         lvjie@hiynn.com         创建文件,实现基本功能
 * =================================================================
 */

public class HttpRequestUtil {

    private HttpRequestUtil(){

    }

    /**
     * 获取Ip地址
     * @param request
     * @return
     */
    public static String getIpAdrress(HttpServletRequest request) {
        String Xip = request.getHeader("X-Real-IP");
        String XFor = request.getHeader("X-Forwarded-For");
        if(StringUtils.isNotEmpty(XFor) && !Constants.HTTP_REQUEST_UNKNONW_VALUE.equalsIgnoreCase(XFor)){
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = XFor.indexOf(",");
            if(index != -1){
                return XFor.substring(0,index);
            }else{
                return XFor;
            }
        }
        XFor = Xip;
        if(StringUtils.isNotEmpty(XFor) && !Constants.HTTP_REQUEST_UNKNONW_VALUE.equalsIgnoreCase(XFor)){
            return XFor;
        }
        if (StringUtils.isBlank(XFor) || Constants.HTTP_REQUEST_UNKNONW_VALUE.equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isBlank(XFor) || Constants.HTTP_REQUEST_UNKNONW_VALUE.equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isBlank(XFor) || Constants.HTTP_REQUEST_UNKNONW_VALUE.equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("HTTP_CLIENT_IP");
        }
        if (StringUtils.isBlank(XFor) || Constants.HTTP_REQUEST_UNKNONW_VALUE.equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (StringUtils.isBlank(XFor) || Constants.HTTP_REQUEST_UNKNONW_VALUE.equalsIgnoreCase(XFor)) {
            XFor = request.getRemoteAddr();
        }
        return XFor;
    }

    /**
     * 获取request中的token和refreshToken
     * @param request
     * @return
     */
    public static String getRefreshTokenFromRequest(HttpServletRequest request){
        String refreshToken = request.getHeader(Constants.HTTP_HEADER_REFRESH_TOKEN_KEY);
        return refreshToken;
    }

    /**
     * 获取request中的token
     * @param request
     * @return
     */
    public static String getTokenFromRequest(HttpServletRequest request){
        String token = request.getHeader(Constants.HTTP_HEADER_TOKEN_KEY);
        return token;
    }
}
